/*
 * @Descripttion: 
 * @version: 
 * @Author: cyj
 * @Date: 2023-03-24 15:53:14
 */

//引入连接数据库
const db = require('../config/db')

const emailLink = require('../dao/emailLink')

//邮箱测试
exports.testEmail = (req, res) => {
    let mail = req.body.mail  //获取前端传入的值
    // console.log(mail);
    emailLink.emailSignUp(mail, res)
}

//联合查找好友、最后一条消息数、未读数据
async function doIt(data, res) {
    let lastmsg = null, tip, friend
    //获取用户数据
    try {
        friend = await getUsers1(data)
    } catch (error) {
        return res.sendMsg(error, 400)
    }
    for (let i = 0; i < friend.length; i++) {
        let obj = {
            uid: data.uid,
            fid: friend[i].id
        }
        //获取对应好友用户的最后一条信息
        try {
            lastmsg = await getOneMsg1(obj)
        } catch (error) {
            return res.sendMsg(error, 400)
        }
        if (lastmsg.types == 0) {

        } else if (lastmsg.types == 1) {
            lastmsg.message = '[图片]'
        } else if (lastmsg.types == 1) {
            lastmsg.message = '[音频]'
        } else if (lastmsg.types == 3) {
            lastmsg.message = '[位置]'
        }
        friend[i].msg = lastmsg.message   //保存到friend数组中  
        try {
            tip = await unReadMsg1(obj)   //获取每个好友用户的未读消息数
        } catch (error) {
            return res.sendMsg(error, 400)
        }
        friend[i].tip = tip.num
    }
    res.sendMsg('success', 200, friend)
}

//获取首页用户列表
exports.getUsers = (data, res) => {
    doIt(data, res)
}

//修改好友消息读取状态 把state=1改为state=0
exports.updateMsg = (data, res) => {
    let sql = 'update message set state = 0 where userid = ? and friendid = ?';
    db.query(sql, [data.fid, data.uid], (err, result) => {
        if (err) return res.sendMsg(err, 400)
        else {
            res.sendMsg('success', 200, result)
        }
    })
}

//获取用户列表
function getUsers1(data) {
    return new Promise((resolve, reject) => {
        //从user表和friend表中多表查询，获取好友id，与某好友的状态，当前用户与某好友最后通讯时间，好友头像，好友username，好友备注,并排序【新到旧】
        let sql = 'SELECT DISTINCT c.friendid as id,d.username,c.nickname,c.state,c.lastTime,d.imgurl from ' +
            '(SELECT b.userid,a.friendid,a.state,a.nickname,a.lastTime FROM `friend` AS a,`user` AS b WHERE a.userid = b.userid AND a.userid = ? and a.state = ?) AS c ,' +
            ' (SELECT `user`.userid,`user`.username,`user`.imgurl FROM `user`,`friend` WHERE `user`.userid = friend.friendid) AS d ' +
            'WHERE c.friendid = d.userid  ORDER BY c.lastTime DESC';
        db.query(sql, [data.uid, data.state], (err, result) => {
            if (err) return reject(err)
            else {
                resolve(result)
                //res.sendMsg('success', 200, result)
            }
        })
    }).catch(err => {
        res.sendMsg(err, 400)
    })
}

//获取一对一消息
function getOneMsg1(data) {
    return new Promise((resolve, reject) => {
        let sql = 'SELECT message,types,time FROM message  WHERE (userid = ? AND friendid = ?) OR (userid = ? AND friendid = ?) ORDER BY time DESC';
        db.query(sql, [data.uid, data.fid, data.fid, data.uid], (err, result) => {
            if (err) return reject(err)
            else {
                resolve(result[0])
                // res.sendMsg('success', 200, result[0])
            }
        })
    }).catch(err => {
        res.sendMsg(err, 400)
    })
}

//汇总消息表中，当前用户和某一个好友用户的未读消息个数
function unReadMsg1(data) {
    return new Promise((resolve, reject) => {
        let sql = 'SELECT COUNT(state) as `num` from message WHERE userid = ? and friendid = ? AND state = 1'
        db.query(sql, [data.fid, data.uid], (err, result) => {
            // console.log(result);
            if (err) return reject(err)
            else {
                resolve(result[0])
                // res.sendMsg('success', 200, result[0])
            }
        })
    }).catch(err => {
        res.sendMsg(err, 400)
    })
}

//联合获取群列表，群最新消息、设置群成员表中某个用户的未读消息数
async function groupdoIt(data, res) {
    let grouplist = null, lastmsg, tip
    //获取群列表数据
    try {
        grouplist = await getGroup1(data)
        console.log(grouplist);
    } catch (error) {
        return res.sendMsg(error, 400)
    }
    for (let i = 0; i < grouplist.length; i++) {
        let groupid = grouplist[i].groupid
        //获取每个群最后一条消息
        try {
            lastmsg = await getGroupMsg1({ gid: groupid }, res)
            console.log(lastmsg);
        } catch (error) {
            return res.sendMsg(error, 400)
        }
        if (lastmsg.types == 0) {
            if (lastmsg.userid == data.uid) {

            } else {
                lastmsg.message = lastmsg.username + '：' + lastmsg.message
            }
        } else if (lastmsg.types == 1) {
            lastmsg.message = lastmsg.username + '：' + '[图片]'
        } else if (lastmsg.types == 1) {
            lastmsg.message = '[音频]'
        } else if (lastmsg.types == 3) {
            lastmsg.message = '[位置]'
        }
        grouplist[i].msg = lastmsg.message   //保存到grouplist数组中  
        try {
            tip = await unReadGroupMsg({ gid: grouplist[i].groupid, uid: data.uid }, res)
        } catch (error) {
            return res.sendMsg(error, 400)
        }
        grouplist[i].tip = tip.count
        let obj = {
            tip: tip.count,
            uid: data.uid,
            gid: grouplist[i].groupid
        }
        //修改成员表中某个用户的未读消息数
        setTip(obj, res)
        // console.log(grouplist[i]);
    }
    res.sendMsg('success', 200, grouplist)
}

// groupdoIt({ uid: 2 }, 1)

//获取群列表
function getGroup1(data, res) {
    return new Promise((resolve, reject) => {
        let sql = 'SELECT a.groupid,a.groupname,a.imgurl,b.tip,b.lastTime FROM `group` AS a,groupuser AS b WHERE a.groupid = b.groupid AND b.userid = ? ORDER BY b.lastTime DESC';
        db.query(sql, [data.uid], (err, result) => {
            // console.log(result);
            if (err) return reject(err)
            else {
                resolve(result)
                // res.sendMsg('success', 200, result)
            }
        })
    }).catch(err => {
        res.sendMsg(err, 400)
    })
}

//获取群消息  最后一条 | 最新消息
function getGroupMsg1(data, res) {
    return new Promise((resolve, reject) => {
        let sql = 'SELECT d.userid,d.username,usernameInGroup,c.message,c.types,time FROM  ' +
            '(SELECT a.userid,MAX(a.time) AS time,a.message,a.types,b.usernameInGroup FROM `groupmsg` AS a,' +
            'groupuser as b WHERE a.groupid=b.groupid AND b.groupid = ? AND a.userid = b.userid GROUP BY a.userid ) as c,' +
            '(SELECT * FROM `user`) AS d WHERE c.userid = d.userid ORDER BY time DESC';
        db.query(sql, [data.gid], (err, result) => {
            if (err) return reject(err)
            else {
                resolve(result[0])
                // res.sendMsg('success', 200, result)
            }
        })
    }).catch(err => {
        res.sendMsg(err, 400)
    })
}

//汇总某个群中某个用户的未读消息数
function unReadGroupMsg(data, res) {
    return new Promise((resolve, reject) => {
        let sql = 'SELECT COUNT(state) as count FROM `groupmsg` as a WHERE a.groupid= ? and a.state =1' +
            ' and a.userid NOT IN (SELECT userid FROM groupmsg WHERE groupmsg.userid = ?)'
        db.query(sql, [data.gid, data.uid], (err, result) => {
            if (err) return reject(err)
            else {
                resolve(result[0])
            }
        })
    }).catch(err => {
        res.sendMsg(err, 400)
    })
}

//设置群成员表中某个用户的未读消息数
function setTip(data, res) {
    let sql = 'UPDATE groupuser SET tip = ? WHERE userid = ? AND groupid = ?'
    db.query(sql, [data.tip, data.uid, data.gid], (err, result) => {
        if (err) return res.sendMsg(err, 500)
        else //console.log('修改成功!');
        {}
    })
}

//获取群列表
exports.getGroup = (data, res) => {
    groupdoIt(data, res)
}

//当某个用户点击某群时，需要把未读消息数置为0  同时把对群内消息全部置为已读
exports.updateGroupMsg = (data, res) => {
    console.log(data);
    let sql = 'UPDATE groupuser SET tip = 0 WHERE groupid = ? AND userid = ?';
    db.query(sql, [data.gid, data.uid], (err, result) => {
        if (err) return res.sendMsg(err, 400)
        else {
            res.sendMsg('success', 200)
        }
    })

}

//同时修改群成员表
// let str = 'UPDATE groupmsg set state = 0 WHERE groupid = ? AND userid = ?'
// db.query(str, [data.gid, data.uid], (err, r) => {
//     if (err) return res.sendMsg(err, 500)
//     else res.sendMsg('success', 200)
// })


